package com.apexwear.apexutils.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.EABleConnectState;
import com.apexwear.apexutils.R;
import com.apexwear.apexutils.adapter.AdapterOtaList;
import com.apexwear.apexutils.api.OnItemClickListener;
import com.apexwear.apexutils.api.OnPositiveClickListener;
import com.apexwear.apexutils.common.Constant;
import com.apexwear.apexutils.data.OtaData;
import com.apexwear.apexutils.databinding.ActivityOtaBinding;
import com.apexwear.apexutils.dialog.UpdateHintDialog;
import com.apexwear.apexutils.model.Ota;
import com.apexwear.apexutils.utils.ShowToast;
import com.cazaea.sweetalert.SweetAlertDialog;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnMultiListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.scwang.smart.refresh.layout.simple.SimpleMultiListener;


import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipInputStream;

import javax.xml.validation.Schema;


public class OtaListActivity extends AppCompatActivity {
    final String TAG = this.getClass().getSimpleName();
    ActivityOtaBinding dataBinding;
    List<Ota> otaList;
    AdapterOtaList adapterOtaList;
    SweetAlertDialog sweetAlertDialog, updateAlertDialog;
    UpdateHintDialog hintAlertDialog;
    int currentPosition;
    ReceiveOtaState receiveOtaState;
    OtaData viewModelProvider;
    boolean is707;
    long lastTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_ota);
        dataBinding.tooBar.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(dataBinding.tooBar);
        getSupportActionBar().setTitle(null);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        dataBinding.tooBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "退出当前页面");
                finish();
            }
        });
        otaList = new ArrayList<>();
        adapterOtaList = new AdapterOtaList(OtaListActivity.this, otaList);
        dataBinding.otaList.setLayoutManager(linearLayoutManager);
        dataBinding.otaList.setAdapter(adapterOtaList);
        viewModelProvider = new ViewModelProvider(OtaListActivity.this).get(OtaData.class);

        adapterOtaList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void clickListener(int position) {
                Log.e(TAG, "版本信息:" + otaList.get(position).getOtaVersion());
                if (EABleManager.getInstance().getDeviceConnectState() == EABleConnectState.STATE_CONNECTED) {
                    currentPosition = position;
                    showHintDialog();

                }

            }
        });
        if (receiveOtaState == null) {
            receiveOtaState = new ReceiveOtaState();
            IntentFilter intentFilter = new IntentFilter(Constant.OTA_RESULT_BROADCAST);
            intentFilter.addAction(Constant.CONNECT_STATE_BROADCAST);
            intentFilter.addAction(Constant.OTA_PROGRESS_BROADCAST);
            LocalBroadcastManager.getInstance(OtaListActivity.this).registerReceiver(receiveOtaState, intentFilter);
        }
        dataBinding.addFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳到文件管理器
                try {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    // intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("*/*");//想要展示的文件类型
                    startActivityForResult(intent, 0x22);
                } catch (Exception e) {

                }

            }
        });
        dataBinding.refresh.setEnableRefresh(true);
        dataBinding.refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData();
            }
        });
        viewModelProvider.otaData.observe(this, new Observer<Ota>() {
            @Override
            public void onChanged(Ota ota) {
                if (ota == null) {
                    if (updateAlertDialog != null && updateAlertDialog.isShowing()) {
                        updateAlertDialog.dismiss();
                    }
                    ShowToast.show(OtaListActivity.this, getString(R.string.file_error));
                    return;
                }
                Log.e(TAG, "获取zip数据成功");
                Intent intent = new Intent(Constant.START_UPDATE_BROADCAST);
                intent.putExtra("ota_info", ota);
                LocalBroadcastManager.getInstance(OtaListActivity.this).sendBroadcast(intent);

            }
        });
        viewModelProvider.watchLive.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    dataBinding.deleteDial.setVisibility(View.VISIBLE);
                } else {
                    dataBinding.deleteDial.setVisibility(View.GONE);
                }
            }
        });
        getData();
        viewModelProvider.is707();
        dataBinding.deleteDial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(OtaListActivity.this, Delete707DialActivity.class));

            }
        });

    }

    private void getData() {
        viewModelProvider.getData().observe(OtaListActivity.this, new Observer<List<Ota>>() {
            @Override
            public void onChanged(List<Ota> otas) {
                dataBinding.refresh.finishRefresh();
                if (otas != null) {
                    otaList.clear();
                    otaList.addAll(otas);
                    adapterOtaList.notifyDataSetChanged();
                } else {
                    Log.e(TAG, "无数据");
                    showNoOtaDialog();
                }
            }
        });
    }

    private void showNoOtaDialog() {
        if (sweetAlertDialog == null) {
            sweetAlertDialog = new SweetAlertDialog(OtaListActivity.this, SweetAlertDialog.WARNING_TYPE);
            sweetAlertDialog.setTitleText(getString(R.string.add_file));
            sweetAlertDialog.setCancelable(true);
            sweetAlertDialog.setCanceledOnTouchOutside(true);
            sweetAlertDialog.setConfirmText(getString(com.cazaea.sweetalert.R.string.dialog_ok));
            sweetAlertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetDialog) {
                    sweetDialog.dismiss();
                    // finish();

                }
            });
        }
        if (!sweetAlertDialog.isShowing()) {
            sweetAlertDialog.show();
        }
    }

    private void showHintDialog() {
        if (hintAlertDialog == null) {
            hintAlertDialog = new UpdateHintDialog(OtaListActivity.this, new OnPositiveClickListener() {
                @Override
                public void clickButton(Object o) {
                    long currentTime = System.currentTimeMillis();
                    if (Math.abs(currentTime - lastTime) < 300) {
                        return;
                    }
                    lastTime = currentTime;
                    Ota ota = otaList.get(currentPosition);
                    if (ota == null || TextUtils.isEmpty(ota.getFilePath())) {
                        return;
                    }
                    File file = new File(ota.getFilePath());
                    if (file == null || !file.exists()) {
                        return;
                    }
                    showUpdateDialog();

                    viewModelProvider.getCurrentOtaInfo(ota);


                }
            });
        }
        if (!hintAlertDialog.isShowing()) {
            hintAlertDialog.show();
        }
    }


    private void showUpdateDialog() {
        if (updateAlertDialog == null) {
            updateAlertDialog = new SweetAlertDialog(OtaListActivity.this, SweetAlertDialog.PROGRESS_TYPE);
            updateAlertDialog.setCancelable(false);
            updateAlertDialog.setCanceledOnTouchOutside(false);
            updateAlertDialog.setTitleText(getString(R.string.updating));

        }
        updateAlertDialog.setContentText(0 + "%");
        if (!updateAlertDialog.isShowing()) {
            updateAlertDialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        if (receiveOtaState != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(receiveOtaState);
            receiveOtaState = null;
        }
        if (hintAlertDialog != null) {
            hintAlertDialog.dismiss();
            hintAlertDialog = null;
        }
        if (updateAlertDialog != null) {
            updateAlertDialog.dismiss();
            updateAlertDialog = null;
        }
        if (sweetAlertDialog != null) {
            sweetAlertDialog.dismiss();
            sweetAlertDialog = null;
        }
        dataBinding.otaList.setLayoutManager(null);
        dataBinding.otaList.setAdapter(null);
        if (adapterOtaList != null) {
            adapterOtaList.destroyAdapter();
            adapterOtaList = null;
        }
        if (dataBinding != null) {
            dataBinding.unbind();
            dataBinding = null;
        }
        otaList = null;
        super.onDestroy();
    }

    class ReceiveOtaState extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action)) {
                if (action.contains(Constant.OTA_RESULT_BROADCAST)) {
                    Log.e(TAG, "收到OTA结果");

                    boolean state = intent.getBooleanExtra("result_state", false);
                    if (is707) {
                        if (!state) {
                            return;
                        }
                        if (updateAlertDialog != null) {
                            updateAlertDialog.dismiss();
                            updateAlertDialog = null;
                        }
                        is707 = false;
                        return;
                    }
                    if (updateAlertDialog != null) {
                        updateAlertDialog.dismiss();
                        updateAlertDialog = null;
                    }
                    if (!state) {
                        ShowToast.show(OtaListActivity.this, getString(R.string.update_failed));
                        return;
                    }


                } else if (action.contains(Constant.CONNECT_STATE_BROADCAST)) {
                    boolean state = intent.getBooleanExtra("connect_state", false);
                    if (!state) {
                        if (is707) {//如果为jieli707平台，不响应
                            // String macAddress = JieliOtaInstance.getInstance().getReconnectAddress();
                            // Log.i(TAG, "重连地址:" + macAddress);
                            // if (!TextUtils.isEmpty(macAddress)) {
                            return;
                            // }

                        }
                        if (updateAlertDialog != null) {
                            if (updateAlertDialog.isShowing()) {
                                updateAlertDialog.dismiss();
                                updateAlertDialog = null;
                                ShowToast.show(OtaListActivity.this, getString(R.string.failed_to_disconnect_ota));
                            }
                        }
                    }
                } else if (action.contains(Constant.OTA_PROGRESS_BROADCAST)) {
                    if (updateAlertDialog != null && updateAlertDialog.isShowing()) {
                        updateAlertDialog.setContentText(intent.getIntExtra("progressValue", 0) + "%");
                        is707 = intent.getBooleanExtra("deviceType", false);
                    }
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x22 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                String scheme = uri.getScheme();
                String path = null;
                if (TextUtils.isEmpty(scheme)) {
                    Log.e(TAG, "sceme不存在");
                    path = uri.getPath();
                } else {
                    Log.e(TAG, "scheme:" + scheme);
                    if (scheme.equalsIgnoreCase(ContentResolver.SCHEME_FILE)) {
                        Log.e(TAG, "是文件");
                        path = uri.getPath();
                    }
                }
                if (TextUtils.isEmpty(path)) {
                    Log.e(TAG, "地址不存在");
                    return;
                }
                File f = new File(path);
                if (f.exists() && f.isFile()) {
                    String sampleName = f.getName();
                    viewModelProvider.saveFile(path, sampleName).observe(OtaListActivity.this, new Observer<Boolean>() {
                        @Override
                        public void onChanged(Boolean aBoolean) {
                            if (aBoolean) {
                                getData();
                            }
                        }
                    });
                }
            }
        }
    }
}
